'use strict';

const Service = require('egg').Service;
const { writeFile } = require('fs');
const { promisify } = require('util');
const writeFileAsync = promisify(writeFile);
const pathCore = require('path');

class QuestionService extends Service {
    /**
     * 问题类型列表
     */
    async readTypeList() {
        let sql = 'select * from question_type order by sort';
        let res = await this.app.mysql.query(sql);
        return res;
    }

    /**
     * 根据试题类型名称，查找某个试题类型
     * @param {*} name
     */
    async findTypeByName(name) {
        let sql = 'select * from question_type where name = ? limit 0, 1';
        let params = [name];
        let res = await this.app.mysql.query(sql, params);
        return res[0];
    }

    /**
     * 添加一个试题类型
     */
    async addType({ name }) {
        // 是否重复
        const type = await this.findTypeByName(name);
        if (type) {
            this.ctx.cast(403, '该类型已存在');
        }
        // 添加
        let res = await this.app.mysql.insert('question_type', {
            id: this.ctx.helper.uuid(),
            name,
        });
        // 返回响应
        return {
            rows: res.affectedRows,
            id: res.insertId,
        };
    }

    /**
     * 根据查询参数获取数据
     */
    async readList({ pagenum = 1, pagesize = 10, sids, etid, qtid }) {
        // 分页参数
        pagenum = Number(pagenum);
        pagesize = Number(pagesize);
        let startIndex = (pagenum - 1) * pagesize;

        // 字段查询 sql
        let select_sql = `
                select
                    q.id,
                    q.title,
                    q.e_tid,
                    et.name as e_tname,
                    q.sid,
                    s.name as sname,
                    q.q_tid,
                    qt.name as q_tname,
                    q.uid,
                    u.nickname
            `;

        // 计数 sql
        let count_sql = `select count(*) as total`;

        // 连表 sql
        let from_sql = `
                from question as q
                    join exam_type as et on q.e_tid = et.id
                    join question_type as qt on q.q_tid = qt.id
                    join subject as s on q.sid = s.id
                    join user as u on q.uid = u.id 
        `;

        // 查询参数
        let search_arr = [];

        // 如果有课程id
        if (sids) {
            // 读取多个课程
            let arr = sids.split(',');

            // 如果只有一个
            if (arr.length === 1) {
                search_arr.push({
                    sql: ' s.id = ? ',
                    params: [arr[0]],
                });

                // 多个
            } else {
                let sids_sql = ` s.id in `;
                let sids_params = [];

                arr.forEach((item, index) => {
                    if (index === 0) {
                        sids_sql += ' (? ';
                        sids_params.push(item);
                        return;
                    }

                    if (index === arr.length - 1) {
                        sids_sql += ' , ?) ';
                        sids_params.push(item);
                        return;
                    }

                    sids_sql += ' ,? ';
                    sids_params.push(item);
                });

                search_arr.push({
                    sql: sids_sql,
                    params: sids_params,
                });
            }
        }

        // 考试类型
        if (etid) {
            search_arr.push({
                sql: ' et.id = ? ',
                params: [etid],
            });
        }

        // 试题类型 id
        if (qtid) {
            search_arr.push({
                sql: 'qt.id = ?',
                params: [qtid],
            });
        }

        // 总参数
        let params = [];

        // 条件 sql
        let where_sql = '';
        search_arr.forEach((item, index) => {
            console.log(index);
            where_sql +=
                index === 0 ? ` where ${item.sql}` : ` and ${item.sql}`;
            params.push(...item.params);
        });

        // 计数查询
        let res = await this.app.mysql.query(
            count_sql + from_sql + where_sql,
            params
        );

        let total = res[0]['total'];

        // 分页查询
        let list = await this.app.mysql.query(
            select_sql + from_sql + where_sql + ' limit ?, ?',
            [...params, startIndex, pagesize]
        );

        return {
            list,
            total,
        };
    }

    /**
     * 添加一个试题
     * @param {*} param0
     */
    async add({ title, content, e_tid, sid, q_tid, answer }) {
        // TODO：校验 e_tid、sid、q_tid 是否存在
        // 生成随机id
        const id = this.ctx.helper.uuid();
        // 拼接内容存储路径
        const filename = `${id}.json`;
        // 组装文件要保存的内容
        const json = { id, content, answer };
        // 写入文件
        await writeFileAsync(
            pathCore.join(this.app.config.rootPath.questions, filename),
            JSON.stringify(json),
            'utf-8'
        );
        // 保存数据库
        let sql =
            'insert into question (id, title, path, e_tid, sid, q_tid, uid) values (?, ?, ?, ?, ?, ?, ?)';
        let params = [
            id,
            title,
            filename,
            e_tid,
            sid,
            q_tid,
            this.ctx.user.uid,
        ];
        let res = await this.app.mysql.query(sql, params);
        return {
            rows: res.affectedRows,
            id: res.insertId,
        };
    }
}

module.exports = QuestionService;
